package guet.dream.tryftl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * Servlet implementation class TryftlServlet
 */
public class TryftlServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Configuration cfg;
       
    
    public void init(){
    	//第一步,初始化FreeMarker配置 ,创建一个配置实例
    	cfg = new Configuration();
    	// 指明ftl模板在web程序中存放的位置 这里指在WEB-INF/template目录下.
    	cfg.setServletContextForTemplateLoading(getServletContext(),
    			"WEB-INF/template");
       // 说明:在真实的产品应用中,各种其他的配置应该在这里显式设置,为了简便,我们就不再此设置了.
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		   String user = request.getParameter("user");
		  //第二步.创建数据模型.
		   Map root = new HashMap();
		   root.put("user", "banxi1988");
		   
		   
		   Map<String, Object> prod =  new HashMap<String, Object>();
		    prod.put("name", "Panda");
		    prod.put("price", "noprice");
		    
		    root.put("prod", prod);
		    
		    //第三步:获取模板对象
		    Template template = cfg.getTemplate("tryftl.ftl");
		    
		    // 第四步: 准备HTTP 响应对象
		    // 使用模板的字符编码作为输入字符编码
		    // 使用text/html作为MIME类型
		    response.setContentType("text/html:charset="+template.getEncoding());
		     PrintWriter out = response.getWriter();
		    
		    //第五步:合并数据模型与模板.
		    
		    try {
				template.process(root, out);
				out.flush();
				out.close();
			} catch (TemplateException e) {
	            throw new ServletException("处理FreeMarker模板时出错!");
			}
		    
		 //  request.setAttribute("user", user);
		 //  request.setAttribute("prod", prod);
		   
		  // RequestDispatcher view = request.getRequestDispatcher("/tryftl.ftl");
		   
		 //  view.forward(request, response);
		   
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

}
